package com.pengpai.pangucms.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pengpai.pangucms.entity.SysUser;
import com.pengpai.pangucms.service.ISysUserRoleService;
import com.pengpai.pangucms.service.ISysUserService;
import com.pengpai.pangucms.utils.PageDomain;
import com.pengpai.pangucms.utils.R;
import com.pengpai.pangucms.utils.ResultTable;
import com.pengpai.pangucms.utils.UserUtils;
import jakarta.annotation.Resource;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * <p>
 * 系统用户表 前端控制器
 * </p>
 *
 * @author lijunjie
 * @since 2023-07-30
 */
@Controller
@RequestMapping("/sysUser")
public class SysUserController {

    @Resource
    private ISysUserService sysUserService;
    @Resource
    private ISysUserRoleService sysUserRoleService;

    @GetMapping("index")
    @PreAuthorize("hasAuthority('sys:user:read')")
    public String index(){
        return "admin/sys_user/sys_user_index";
    }

    @GetMapping("add")
    @PreAuthorize("hasAuthority('sys:user:create')")
    public String add(){
        return "admin/sys_user/sys_user_add";
    }

    @PostMapping("create")
    @ResponseBody
    @PreAuthorize("hasAuthority('sys:user:create')")
    public R create(SysUser sysUser){
        sysUser.setPassword(UserUtils.encoder(sysUser.getPassword()));
        sysUser.setCreateUser(UserUtils.CurrentUserName());
        sysUser.setCreateTime(LocalDateTime.now());
        sysUser.setUpdateUser(UserUtils.CurrentUserName());
        sysUser.setUpdateTime(LocalDateTime.now());

        sysUserService.save(sysUser);
        return R.success();
    }

    @PostMapping("update")
    @ResponseBody
    @PreAuthorize("hasAuthority('sys:user:update')")
    public R update(SysUser sysUser){
        // 查询原用户信息  用户名、真实姓名不允许进行修改 不允许为空或空串
        if(sysUser == null || sysUser.getUserName() == null || sysUser.getTrueName() == null
                || "".equals(sysUser.getUserName()) || "".equals(sysUser.getTrueName())){
            return R.fail("用户名、真实姓名不允许进行修改!");
        }
        SysUser originalUser= sysUserService.getById(sysUser.getUserId());
        if(!sysUser.getUserName().equals(originalUser.getUserName()) || !sysUser.getTrueName().equals(originalUser.getTrueName())){
            return R.fail("用户名、真实姓名不允许进行修改!");
        }
        // creater isdel orderId等字段不允许修改
        if((sysUser.getCreateUser() != null && !sysUser.getCreateUser().equals(originalUser.getCreateUser()))
                || (sysUser.getIsDel() != null && !sysUser.getIsDel().equals(originalUser.getIsDel()))
                || (sysUser.getOrderId() != null && !sysUser.getOrderId().equals(originalUser.getOrderId()))){
            return R.fail("不允许恶意修改其他字段!");
        }
        sysUser.setUpdateUser(UserUtils.CurrentUserName());
        sysUser.setUpdateTime(LocalDateTime.now());
        sysUserService.updateById(sysUser);
        return R.success("用户信息更新成功！");
    }

    @GetMapping("/list")
    @ResponseBody
    @PreAuthorize("hasAuthority('sys:user:read')")
    public ResultTable data(SysUser user, PageDomain pageDomain) {
        Page<SysUser> sysUserPage = new Page<>(pageDomain.getPage(), pageDomain.getLimit());
        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.like(StrUtil.isNotBlank(user.getUserName()), "user_name", user.getUserName())
                .or().like(StrUtil.isNotBlank(user.getTrueName()), "true_name", user.getTrueName()).orderByAsc("order_id");
        queryWrapper.select(SysUser.class, u -> !u.getColumn().equals("password"));
        List<SysUser> sysUserList = sysUserService.page(sysUserPage,queryWrapper).getRecords();
        Collections.sort(sysUserList, new Comparator<SysUser>() {
            @Override
            public int compare(SysUser o1, SysUser o2) {
                if(o1.getOrderId() == null || "".equals(o1.getOrderId())) return -1;
                if(o2.getOrderId() == null || "".equals(o2.getOrderId())) return -1;
                return o1.getOrderId() - o2.getOrderId();
            }
        });
        return ResultTable.pageTable(sysUserPage.getTotal(), sysUserList);
    }


    @PostMapping("/del")
    @ResponseBody
    @PreAuthorize("hasAuthority('sys:user:delete')")
    public R del(String ids){

        List<Long> list = null;
        if(StrUtil.isNotBlank(ids)){
            list =Stream.of(ids.split(",")).map(Long::parseLong).collect(Collectors.toList());
        }
        sysUserService.removeBatchByIds(list);
        return R.success();
    }
    @GetMapping("/edit")
    @PreAuthorize("hasAuthority('sys:user:update')")
    public String edit(String id, Model model){
        SysUser sysUser = sysUserService.getById(id);
        model.addAttribute("user", sysUser);
        return "admin/sys_user/sys_user_edit";
    }

    @GetMapping("/grant")
    @PreAuthorize("hasAuthority('sys:user:grant')")
    public String grant(Integer id, Model model){
        SysUser sysUser = sysUserService.getById(id);
        model.addAttribute("user", sysUser);
        List<Map<String, Object>> userRoles = sysUserRoleService.getUserRoleByUid(id);
        model.addAttribute("roles", userRoles);
        return "admin/sys_user/sys_user_grant";
    }
    @PostMapping("/updateUserRole")
    @ResponseBody
    @PreAuthorize("hasAuthority('sys:user:grant')")
    public R update(Long userId, String roleIds){
        List<String> roles = Arrays.stream(roleIds.split(",")).toList();
        sysUserRoleService.grantByUid(userId, roles);
        return R.success();
    }

    @GetMapping("/updatePassPage")
    public String updatePassPage(){
        return "admin/sys_user/sys_user_updatePW";
    }
    @PostMapping("/updatePassword")
    @ResponseBody
    @PreAuthorize("hasAuthority('sys:user:update')")
    public R updatePassword(String old_password, String new_password){
        if(new_password==null || old_password == null || "".equals(new_password)) return R.fail("密码不能设置为空");
        boolean res = sysUserService.updatePassword(old_password, new_password);
        if(res){
            return R.success();
        }else {
            return R.fail("密码修改失败");
        }
    }
}
